import {messages} from "share/common";
import React from 'react'

import {Input, message, Tag, Form, Modal, Table} from 'antd';
import 'styles/financial-management/scan-send.scss';
import ScanSendService from 'containers/financial-management/scan-send/scan-send.service';
import SearchArea from 'components/search-area';

import moment from "moment/moment";
import FileSaver from "file-saver";

class ScanSend extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [
        {title: messages('financial-management.key286'/*单据编号*/), dataIndex: 'businessCode'}, // 单据编号
        {
          title: messages('financial-management.key287'/*寄出时间*/),
          dataIndex: 'createdDate',
          render: (value, record) => moment(record.createdDate).format('YYYY-MM-DD hh:mm')
        } // 寄出时间
      ], // 表头
      data: [], // 表格数据
      confirmLoading: false, // 导出加载
      loading: false, // 数据加载
      showModal: false, // 搜索结果弹窗
      sendList: [],
      searchForm: [
        {
          type: 'rangePicker', id: 'dateRange', label: `${messages('financial-management.key287'/*寄出时间*/)} : `
        }
        // {
        //   label: `${messages('scan-receive.sendDate')} : `, type: 'items', colSpan: 12, labelCol: 4, id: 'dateRange', items: [
        //     {type: 'date', id: 'startDate', event: 'DATE'},
        //     {type: 'date', id: 'endDate', event: 'DATE'}
        //   ]
        // }
      ],
      searchParams: {},
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0
      }
    };
  }


  componentDidMount() {
    this.input.focus();
  }

  // 搜索
  search = (values) => {
    // values = {...values};
    // values.startDate && (values.startDate = moment(values.startDate).format('YYYY-MM-DD 00:00:00'));
    // values.endDate && (values.endDate = moment(values.endDate).format('YYYY-MM-DD 23:59:59'));
    let searchParams = {};
    values.dateRange && values.dateRange[0] && (searchParams.startDate = moment(values.dateRange[0]).format('YYYY-MM-DD 00:00:00'));
    values.dateRange && values.dateRange[1] && (searchParams.endDate = moment(values.dateRange[1]).format('YYYY-MM-DD 23:59:59'));

    this.setState({searchParams, page: 0, showModal: true}, () => {
      this.getList();
    });
  };
  getList = () => {
    const {searchParams, page, pageSize} = this.state;
    let params = {...searchParams};
    params.page = page;
    params.size = pageSize;
    this.setState({loading: true});
    ScanSendService.getData(params).then(res => {
      this.setState({
        data: res.data,
        loading: false,
        pagination: {
          total: Number(res.headers['x-total-count']) || 0,
          current: page + 1,
          onChange: this.onChangePaper,
          pageSize: pageSize
        }
      });
    }).catch(err => {
      message.error(err.response.data.message);
    }).finally(() => {
      this.setState({loading: false});
    });
  };
  onChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({page: page - 1}, () => {
        this.getList()
      })
    }
  };
  handlePressEnter = (e) => {
    let {sendList} = this.state;
    ScanSendService.send(e.target.value).then(res => {
      if (res.data.code === '0000') {
        sendList.unshift(res.data.businessCode);
        message.success(res.data.msg);
      } else {
        message.error(res.data.msg);
      }
      this.props.form.resetFields();
    })
  };
  // 关闭
  handleCancel = () => {
    this.setState({showModal: false});

  };
  // 导出
  handleExport = () => {
    const {searchParams} = this.state;
    if (this.state.data.length < 1) {
      message.error(messages('financial-management.key288'/*该时间段内没有单据寄出*/)); // 该时间段内没有单据寄出
      return !1;
    }
    this.setState({confirmLoading: true});
    let hide = message.loading(messages('financial-management.key82'/*正在生成文件..*/));
    /*正在生成文件..*/
    ScanSendService.exportData({...searchParams}).then(res => {
      let b = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
      let name = messages('financial-management.key289'/*已寄出单据*/);
      FileSaver.saveAs(b, `${name}.xlsx`);
    }).catch(() => {
      /*下载失败，请重试*/
      message.error(messages('financial-management.key83'/*下载失败，请重试*/));
    }).finally(() => {
      this.setState({confirmLoading: false});
      hide();
    });
  };

  render() {
    const {sendList, searchForm, showModal, loading, pagination, columns, data, confirmLoading} = this.state;
    return (
      <div className="scan-send">
        <SearchArea
          searchForm={searchForm}
          submitHandle={this.search}
        />
        <h1>{messages('financial-management.key290'/*扫码寄单*/)}</h1>
        <p>{messages('financial-management.key291'/*只可扫描审批通过的单据*/)}</p>
        {this.props.form.getFieldDecorator('code')(
          <Input
            onPressEnter={this.handlePressEnter}
            placeholder={messages('financial-management.key292'/*请使用扫码枪*/)}
            ref={input => this.input = input}
            className="input-search"
          />
        )}
        <div className="send-area">
          <h3 className="send-title">{messages('financial-management.key289'/*已寄出单据*/)}</h3>
          <div className="send-result">
            {sendList.map((item, index) =>
              <Tag key={index}>{item}</Tag>
            )}
          </div>
        </div>
        <Modal
          title={messages('financial-management.key293'/*搜索结果*/)}
          okText={messages('financial-management.key294'/*导出数据*/)}
          cancelText={messages('financial-management.key295'/*关闭*/)}
          visible={showModal}
          confirmLoading={confirmLoading}
          wrapClassName="scan-list-modal"
          onOk={this.handleExport}
          onCancel={this.handleCancel}
        >
          <Table
            rowKey="id"
            columns={columns}
            dataSource={data}
            pagination={pagination}
            loading={loading}
            bordered
            size="middle"
          />
        </Modal>
      </div>
    )
  }

}

ScanSend.contextTypes = {
  router: React.PropTypes.object
};

const WrappedScanSend = Form.create()(ScanSend);

export default WrappedScanSend;
